package com.honey.mybatis.generator.dao.method;

import java.util.List;

import com.honey.compilation.java.AbstractJavaCompilation;
import com.honey.compilation.java.ElseBlock;
import com.honey.compilation.java.IfBlock;
import com.honey.compilation.java.Interface;
import com.honey.compilation.java.Method;
import com.honey.core.dbmapping.introspect.IntrospectSchema;
import com.honey.core.dbmapping.introspect.IntrospectSchemaColumn;
import com.honey.core.dbmapping.introspect.IntrospectTableColumn;
import com.honey.core.dbmapping.structure.TableColumn;
import com.honey.core.types.FullyQualifiedJavaType;
import com.honey.core.types.JDKFullyQualifiedJavaType;
import com.honey.core.utils.JavaBeansUtil;
import com.honey.mybatis.generator.MybatisPlugin;
import com.honey.mybatis.generator.dao.DaoConstant;

/**
 * 按照primaryKey查询
 * @author Administrator
 *
 */
public class SaveMethod extends AbstractCreateInterfaceMethod{
	
	private static final String METHOD_NAME="save";

	private static final FullyQualifiedJavaType RETURN_TYPE = JDKFullyQualifiedJavaType.getIntInstance();

	private FullyQualifiedJavaType UPDATE_TYPE;
	
	private boolean isUseSession = false ;
	private IntrospectSchema introspectSchema=null;
	public SaveMethod(
			AbstractJavaCompilation clazz, MybatisPlugin belongPlugin,
			IntrospectSchema introspectSchema,
			IntrospectSchemaColumn introspectSchemaColumn
			) {
		this(clazz, belongPlugin, introspectSchema, introspectSchemaColumn, false);
		this.introspectSchema = introspectSchema;
		
	}
	
	public SaveMethod(
			AbstractJavaCompilation clazz, MybatisPlugin belongPlugin,
			IntrospectSchema introspectSchema,
			IntrospectSchemaColumn introspectSchemaColumn,
			boolean  isUseSession
			) {
		super(clazz, belongPlugin, introspectSchema, introspectSchemaColumn);
		this.isUseSession = isUseSession;
		if( clazz instanceof Interface ){
			UPDATE_TYPE = new FullyQualifiedJavaType("E");
		}else{
			UPDATE_TYPE = super.getEntityClassType(introspectSchema.getSchema());
		}
	}
	
	/* (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#addBody(com.honey.compilation.java.Method)
	 */
	@Override
	protected void addBody(Method method) {	
		List<TableColumn> columns = ((IntrospectTableColumn)introspectSchemaColumn).primaryKeyColumns();
		
		method.addBodyLine("int key = -1;");
		 boolean comma = false;
		 StringBuilder sb = new StringBuilder();
		for(TableColumn tc : columns){
			 if (comma)sb.append(" && "); else comma = true;
			 sb.append(super.getEntityVariableName(introspectSchema.getSchema())).append(".").append(JavaBeansUtil.getGetterMethodName(super.getMethodName(tc), tc.getFullyQualifiedJavaType()))
			 .append("() == null");
		}
		IfBlock ifBlock = new IfBlock (sb.toString()); 
		ifBlock.addBodyLine(
				new StringBuilder()
				.append(" key = ")
				//.append("super.")
				.append(mybatisPlugin.getDependentModel().call(null))
				.append("insert (")
				.append( isUseSession()?DaoConstant.SQL_SESSION_NAME+" , ":"" )
				//.append(DaoConstant.INSERT_FIELD_NAME)
				.append(super.getMapperId().getInsertMapperId())
				.append(" , ")
				.append(super.getEntityVariableName(introspectSchema.getSchema())).append(" )")
				.toString()
		);
		method.addBlocks(ifBlock);
		ElseBlock elseBlock = new ElseBlock();
		elseBlock.addBodyLine(
				new StringBuilder()
				.append(" key = ")
				//.append("super.")
				.append(mybatisPlugin.getDependentModel().call(null))
				.append("update (")
				.append( isUseSession()?DaoConstant.SQL_SESSION_NAME+" , ":"" )
				//.append(DaoConstant.UPDATE_BY_PRIMARYKEY_FIELD_NAME)
				.append(super.getMapperId().getUpdateByPrimaryKeyMapperId())
				.append(" , ")
				.append(super.getEntityVariableName(introspectSchema.getSchema())).append(" )")
				.toString()
		);
		method.addBlocks(elseBlock);
		method.addBodyLine("return key ");
	}

	/*
	 * (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#getMethodName()
	 */
	@Override
	protected String getMethodName() {		
		String answer = null;
		if(introspectSchema != null && introspectSchema.getSchema().isIncludePrimaryKeyColumn())
			if( mybatisPlugin.isEnableUpdate() &&  mybatisPlugin.isEnableInsert() ){
				if( !isUseSession ){
					answer = METHOD_NAME;
				}else if( isUseSession  && mybatisPlugin.isEnableUseSqlSession() ){
					answer = METHOD_NAME;
				}
			}
		return answer;
	}
	
	/* (non-Javadoc)
	 * @see com.honey.mybatis.generator.dao.method.AbstractCreateInterfaceMethod#getUpdateEntityType()
	 */
	@Override
	public FullyQualifiedJavaType getUpdateEntityType() {
		
		return UPDATE_TYPE;
	}

	/**
	 * @return the isUseSession
	 */
	@Override
	public final boolean isUseSession() {
		return isUseSession;
	}

	/* (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#getJavaDoc()
	 */
	@Override
	protected String[] getJavaDoc() {
		String[] answer = new String[]{
			"保存entity,如果entity中包含主键则更新实体,如果entity中不包含主键则插入实体。方法返回影响记录集的数量。"
		};
		return answer;
	}

	/* (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#getReturnType()
	 */
	@Override
	protected FullyQualifiedJavaType getReturnType() {
		
		return RETURN_TYPE;
	}

	/* (non-Javadoc)
	 * @see com.honey.mybatis.generator.dao.method.AbstractCreateInterfaceMethod#isCondition()
	 */
	@Override
	public boolean isCondition() {
		
		return false;
	}

	
}
